package com.xk._01基础篇._06二叉搜索树;

import com.xk._01基础篇._06二叉搜索树.printer.BinaryTreeInfo;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @description:
 * @author: xu
 * @date: 2022/9/20 1:01
 */
public class BinarySearchTree01<E> implements BinaryTreeInfo {
    private int size;
    private Node<E> root; // 根结点

    private Comparator<E> comparator;

    public BinarySearchTree01(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public BinarySearchTree01() {
        this(null);
    }

    private static class Node<E> {
        E elememt;
        Node<E> parent; // 父结点
        Node<E> left; // 左结点
        Node<E> right; // 右结点
        public Node(E elememt, Node<E> parent) {
            this.elememt = elememt;
            this.parent = parent;
        }
        public boolean isLeaf(){
            return left == null && right == null;
        }
        public boolean hasTwoChildren() {
            return left != null && right != null;
        }
    }

    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public void clear(){
        root = null;
        size = 0;
    }

    public void add(E element){
        elementNotNullCheck(element);
        if (root == null) { // 添加第一个结点
            root = new Node<>(element, null);
            size++;
            return;
        }

        // 添加的不是第一个结点
        // 找到父节点
        Node<E> node = root;
        Node<E> parent = root;
        int cmp = 0;
        while (node != null){
            cmp = compare(element, node.elememt);
            parent = node;
            if (cmp < 0){
                node = node.left;
            } else if (cmp > 0) {
                node = node.right;
            } else { // 相等
                node.elememt = element;
                return;
            }
        }
        //看看插入到父节点的哪个位置
        Node<E> newNode = new Node<>(element, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
    }

    public void remove(E element){
        remove(node(element));
    }
    private void remove(Node<E> node){
        if (node == null) return;
        size--;

        // 度为2的节点
        if (node.hasTwoChildren()){
            // 找到后继结点
            Node<E> s = successor(node);
            // 用后继结点的值覆盖将删除结点的值
            node.elememt = s.elememt;
            // 删除后继结点
            node = s;
        }

        //删除node结点（此时node的度必为1或者0）
        Node<E> replacement = node.left != null ? node.left : node.right;
        if (replacement != null){
            // node 度为 1
            // 更改子结点的parent
            replacement.parent = node.parent;
            // 更改parent的left、right的指向
            if (node.parent == null) {
                // node是度为1的根结点
                root = replacement;
            } else if (node == node.parent.left) {
                node.parent.left = replacement;
            } else {
                node.parent.right = replacement;
            }
        } else if (node.parent == null){
            // node 度为 0，node为根结点并且是叶子结点
            root = null;
        } else {
            // node是叶子结点，但不是根节点
            if (node == node.parent.left) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
        }
    }

    /**
     * 根据元素查找对应的结点
     * @param element
     * @return
     */
    private Node<E> node(E element){
        Node<E> node = root;
        while (node != null){
            int cmp = compare(element, node.elememt);
            if (cmp == 0) return node;
            else if (cmp > 0) node = node.right;
            else node = node.left;
        }
        return node;
    }

    public boolean contains(E element){
        return node(element) != null;
    }

    /**
     * 计算树的高度
     * @return
     */
    public int height(){
        return height(root);
    }
    private int height(Node<E> node){
        /*

        //递归
        if (node == null) return 0;
        return 1 + Math.max(height(node.left), height(node.right));

        */

        // 非递归
        if (node == null) return 0;
        int height = 0; // 树的高度
        int levelSize = 1; // 存储着每一层的元素数量
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty()){
            Node<E> poll = queue.poll();
            levelSize--;
            if (poll.left != null)  queue.offer(poll.left);
            if (poll.right != null) queue.offer(poll.right);
            if (levelSize == 0) { // 意味着即将访问下一层
                levelSize = queue.size();
                height++;
            }
        }
        return height;
    }

    /**
     * 判断此树是否是完全二叉树 层序遍历
     * @return
     */
    public boolean isComplete(){
        if (root == null) return false;
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(root);

        boolean leaf = false;
        while (!queue.isEmpty()){
            Node<E> node = queue.poll();
            if (leaf && !node.isLeaf()) return false;

            if (node.left != null){
                queue.offer(node.left);
            } else if (node.right != null) {
                // poll.left == null && poll.right != null
                return false;
            }

            if (node.right != null) {
                queue.offer(node.right);
            } else {
                // poll.left == null && poll.right == null
                // poll.left != null && poll.right == null
                leaf = true;
            }
        }
        return true;
    }
    /*
    public boolean isComplete(){
        if (root == null) return false;
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(root);

        boolean leaf = false;
        while (!queue.isEmpty()){
            Node<E> poll = queue.poll();
            if (leaf && !poll.isLeaf()) return false;
            if (poll.hasTwoChildren()) {
                queue.offer(poll.left);
                queue.offer(poll.right);
            } else if (poll.left == null && poll.right != null) {
                // 这种情况是只有右子树，肯定不是完全二叉树，返回false
                return false;
            } else {
                // 只有左子树或者无子树的情况下
                // 此时队列里面的所有节点都应该是叶子结点，则为完全二叉树
                leaf = true;
                if (poll.left != null){
                    queue.offer(poll);
                }
            }
        }
        return true;
    }
    */

    /**
     * 前序遍历
     */
    public void preOrder(Visitor<E> visitor){
        if (visitor == null) return;
        preOrder(root, visitor);
    }
    private void preOrder(Node<E> node, Visitor<E> visitor){
        if(node == null || visitor.stop) return;
        visitor.stop = visitor.visit(node.elememt);
        preOrder(node.left, visitor);
        preOrder(node.right, visitor);
    }

    /**
     * 中序遍历
     */
    public void inOrder(Visitor<E> visitor){
        if (visitor == null) return;
        inOrder(root, visitor);
    }
    private void inOrder(Node<E> node, Visitor<E> visitor){
        if(node == null || visitor.stop) return;
        inOrder(node.left, visitor);
        if (visitor.stop) return;
        visitor.stop = visitor.visit(node.elememt);
        inOrder(node.right, visitor);
    }

    /**
     * 后序遍历
     */
    public void postOrder(Visitor<E> visitor){
        if (visitor == null) return;
        postOrder(root, visitor);
    }
    private void postOrder(Node<E> node, Visitor<E> visitor){
        if(node == null || visitor.stop) return;
        postOrder(node.left, visitor);
        postOrder(node.right, visitor);
        if (visitor.stop) return;
        visitor.stop = visitor.visit(node.elememt);
    }

    /**
     * 层序遍历
     */
    public void levelOrder(Visitor<E> visitor){
        if (root == null || visitor == null) return;
        Node<E> node = root;
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty()){
            Node<E> poll = queue.poll();
            if (visitor.visit(poll.elememt)) return;
            if (poll.left != null) queue.offer(poll.left);
            if (poll.right != null) queue.offer(poll.right);
        }
    }

    public static abstract class Visitor<E> {
        boolean stop;
        abstract boolean visit(E element);
    }

    /**
     * @return
     *      返回值等于0，代表e1和e2相等
     *      返回值大于0，代表e1大于e2
     *      返回值小于0，代表e1小于e2
     */
    private int compare(E e1, E e2){
        if (comparator != null){
            return comparator.compare(e1, e2);
        }
        return ((Comparable<E>) e1).compareTo(e2);
    }

    private void elementNotNullCheck(E element) {
        if (element == null){
            throw new IllegalArgumentException("element must not be null");
        }
    }

    /**
     * 获取指定结点的前驱结点
     * 前驱结点：中序遍历时该结点的前一个结点
     * @param node
     * @return
     */
    private Node<E> predecessor(Node<E> node) {
        if (node == null) return null;

        // 前驱结点在左子树当中(left.right.right.right......)
        Node<E> p = node.left;
        if (p != null) {
            while (p.right != null){
                p = p.right;
            }
            return p;
        }

        // 从祖父结点中寻找前驱结点
        while (node.parent != null && node == node.parent.left){
            node = node.parent;
        }
        // node.parent == null
        // node == node.parent.right
        return node.parent;
    }

    /**
     * 获取指定结点的后继结点
     * 后继结点：中序遍历时该结点的后一个结点
     * @param node
     * @return
     */
    private Node<E> successor(Node<E> node) {
        if (node == null) return null;

        // 前驱结点在左子树当中(left.right.right.right......)
        Node<E> p = node.right;
        if (p != null) {
            while (p.left != null){
                p = p.left;
            }
            return p;
        }

        // 从祖父结点中寻找前驱结点
        while (node.parent != null && node == node.parent.right){
            node = node.parent;
        }
        // node.parent == null
        // node == node.parent.right
        return node.parent;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        toString(root, sb, "");
        return sb.toString();
    }
    private void toString(Node<E> node, StringBuilder sb, String prefix) {
        if (node == null) return;
        sb.append(prefix).append(node.elememt).append("\n");
        toString(node.left, sb, prefix + "L---");
        toString(node.right, sb, prefix + "R---");
    }

    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<E>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<E>) node).right;
    }

    @Override
    public Object string(Object node) {
        Node<E> myNode = (Node<E>) node;
        String parentStr = "null";
        if (myNode.parent != null){
            parentStr = myNode.parent.elememt.toString();
        }
        return ((Node<E>) node).elememt + "_p(" + parentStr + ")";
    }

    // 前序遍历
    public void preorderTraversal(){
        preorderTraversal(root);
    }
    // 前序遍历 递归
    private void preorderTraversal(Node<E> node){
        if (node == null) return;
        System.out.print(node.elememt + " ");
        preorderTraversal(node.left);
        preorderTraversal(node.right);
    }

    // 中序遍历
    public void inorderTraversal(){
        inorderTraversal(root);
    }
    // 中序遍历 递归
    private void inorderTraversal(Node<E> node){
        if (node == null) return;
        inorderTraversal(node.left);
        System.out.print(node.elememt + " ");
        inorderTraversal(node.right);
    }

    // 后序遍历
    public void postorderTraversal(){
        postorderTraversal(root);
    }
    // 后序遍历 递归
    private void postorderTraversal(Node<E> node){
        if (node == null) return;
        postorderTraversal(node.left);
        postorderTraversal(node.right);
        System.out.print(node.elememt + " ");
    }

    // 层序遍历
    public void levelOrderTraversal(){
        levelOrderTraversal(root);
    }
    // 层序遍历 队列
    private void levelOrderTraversal(Node<E> node){
        if (node == null) return;
        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(node);
        while (!queue.isEmpty()){
            Node<E> poll = queue.poll();
            System.out.print(poll.elememt + " ");
            if (poll.left != null) queue.offer(poll.left);
            if (poll.right != null) queue.offer(poll.right);
        }
    }
}
